package person.wend.springbootlearnexample.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.validation.DefaultMessageCodesResolver;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebMvc
public class SelfSpringMVCConfig implements WebMvcConfigurer {

    // 配置 ContentNegotiatingViewResolver
    @Bean
    public ViewResolver contentNegotiatingViewResolver() {
        ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
        List<ViewResolver> resolvers = new ArrayList<>();
        resolvers.add(beanNameViewResolver()); // 添加 BeanNameViewResolver 到视图解析器列表
        resolver.setViewResolvers(resolvers);
        return resolver;
    }

    // 配置 BeanNameViewResolver
    @Bean
    public ViewResolver beanNameViewResolver() {
        return new BeanNameViewResolver();
    }

    // 自定义一个 View，这里以 JSON 视图为例
    @Bean
    public ModelAndView myModelAndView() {
        ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
        mav.addObject("code", 200);
        mav.addObject("message", "success");
        return mav;
    }

    // 配置 MessageSource，用于提供消息文本
    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages"); // 消息文件的基础名称，将从类路径下查找 messages.properties 文件
        return messageSource;
    }

    // 配置 MessageCodesResolver
    @Bean
    public MessageCodesResolver messageCodesResolver() {
        DefaultMessageCodesResolver resolver = new DefaultMessageCodesResolver();
        resolver.setPrefix("error."); // 设置消息代码的前缀
        return resolver;
    }

    // 配置 ConversionService
    @Bean
    public ConversionService conversionService() {
        ConversionService conversionService = new DefaultFormattingConversionService();
        conversionService.convert("123", Integer.class); // 将字符串 "123" 转换为整数 123
        return new DefaultFormattingConversionService();
    }

}